#include "board.h"
#include <rthw.h>
#include <rtthread.h>

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
#define RT_HEAP_SIZE 1024


static uint32_t rt_heap[RT_HEAP_SIZE];	// heap default size: 4K(1024 * 4)


RT_WEAK void *rt_heap_begin_get(void)
{
    return rt_heap;
}

RT_WEAK void *rt_heap_end_get(void)
{
    return rt_heap + RT_HEAP_SIZE;
}
#endif

/**
 * This function will initial your board.
 */
void rt_hw_board_init()
{	
	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_CRC, ENABLE);
	SysTick_Config(SystemCoreClock / RT_TICK_PER_SECOND);
	
	LED_GPIO_Config();
	USART_Config();
	XPT2046_Init();

    /* Call components board initial (use INIT_BOARD_EXPORT()) */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif
    
#if defined(RT_USING_CONSOLE) && defined(RT_USING_DEVICE)
	rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif
    
#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
    rt_system_heap_init(rt_heap_begin_get(), rt_heap_end_get());
#endif
}

void SysTick_Handler(void)
{
	/* enter interrupt */
	rt_interrupt_enter();

	rt_tick_increase();

	/* leave interrupt */
	rt_interrupt_leave();
}

void rt_hw_console_output(const char *str)
{
	rt_enter_critical();
	
	while(*str != '\0')
	{
		if(*str=='\n')
		{
			USART_SendData(DEBUG_USARTx, '\r');
			while(USART_GetFlagStatus(DEBUG_USARTx,USART_FLAG_TXE) == RESET);
		}
		USART_SendData(DEBUG_USARTx, *str++);
		while(USART_GetFlagStatus(DEBUG_USARTx,USART_FLAG_TXE) == RESET);
	}
	rt_exit_critical();
}

